﻿using System;
using System.Collections.Generic;
using System.Text;
using Barbar.MapReport.Common.Drawing.Commands;
using Barbar.MapReport.Common.Drawing;
using System.Collections.ObjectModel;
using Barbar.MapReport.Common;
using Barbar.MapReport.DataSource;
using Barbar.MapReport.HtmlRender.Operations.Legends;

namespace Barbar.MapReport.HtmlRender.Operations.Regions {
  [Serializable]
  internal class RegionsWithBusinessProcessingData {
    private Collection<RegionListWrapper<BusinessRegionList>> m_ListOfRegionList = new Collection<RegionListWrapper<BusinessRegionList>>();
    private LegendRangeList m_LegendRangesList;
    private RegionOptions m_RegionOptions;
    private SerializedColor m_StrokeColor;
    private int m_StrokeWeight;

    public LegendRangeList LegendRangeList {
      get { return m_LegendRangesList; }
    }

    public RegionOptions RegionOptions {
      get { return m_RegionOptions; }
    }

    public SerializedColor StrokeColor {
      get { return m_StrokeColor; }
    }

    public int StrokeWeight {
      get { return m_StrokeWeight; }
    }
    
    public RegionsWithBusinessProcessingData(AddRegionsWithBusinessProcessingCommand command) {
      m_RegionOptions = command.RegionOptions;
      m_StrokeColor = command.StrokeColor;
      m_StrokeWeight = command.StrokeWeight;

      foreach (BusinessRegionList regionList in command.Regions) {
        m_ListOfRegionList.Add(new RegionListWrapper<BusinessRegionList>(regionList));
      }

      LegendFactory factory = new LegendFactory(BusinessValueHelper.ConvertEnumeration<BusinessRegionList>(command.Regions), command.RegionOptions.CategoriesCount, command.LegendDescription);
      m_LegendRangesList = factory.CreateLegend();
    }

    public IEnumerable<BusinessRegionList> GetValidBusinessRegionLists(IGeoBound bound, ZoomLevel zoomLevel) {
      foreach (RegionListWrapper<BusinessRegionList> wrapper in m_ListOfRegionList) {
        if (GeoBound.Intersect(bound, wrapper)) {
          BusinessRegionList regionList = new BusinessRegionList();
          regionList.ToolTip = wrapper.RegionList.ToolTip;
          regionList.Value = wrapper.RegionList.Value;
          foreach (string regionId in wrapper.RegionList.RegionIds) {
            Polygon polygon = DataSourceManager.GetRegionGeometry(regionId, zoomLevel);
            if (GeoBound.Intersect(bound, polygon))
              regionList.RegionIds.Add(regionId);
          }
          yield return regionList;
        }
      }
    }
  }
}
